const nodemailer = require('nodemailer');
const config = require('./config-loader');

// 创建邮件发送器
function createTransporter() {
    // 根据邮箱服务类型创建不同的配置
    const emailService = config.email.service;

    // 针对163邮箱的特殊配置
    if (emailService === '163') {
        return nodemailer.createTransport({
            host: 'smtp.163.com',
            port: 465,
            secure: true, // 使用SSL
            auth: {
                user: config.email.user,
                pass: config.email.pass // 注意：这里应该使用授权码，而不是邮箱密码
            }
        });
    }
    // 针对其他常见邮箱的配置
    else {
        return nodemailer.createTransport({
            service: config.email.service,
            auth: {
                user: config.email.user,
                pass: config.email.pass
            }
        });
    }
}

// 发送部署开始通知
async function sendDeployStartNotification(repoName, branch) {
    const transporter = createTransporter();

    const subject = `[自动部署通知] ${repoName} (${branch}) 开始部署`;

    const html = `
    <h2>自动部署通知</h2>
    <p><strong>仓库:</strong> ${repoName}</p>
    <p><strong>分支:</strong> ${branch}</p>
    <p><strong>状态:</strong> <span style="color: blue">开始部署</span></p>
    <p><strong>时间:</strong> ${new Date().toLocaleString()}</p>
    <p>系统正在执行自动部署流程，稍后将发送部署结果通知。</p>
  `;

    try {
        await transporter.sendMail({
            from: config.email.user,
            to: config.email.to,
            subject: subject,
            html: html
        });
        console.log('部署开始通知邮件已发送');
        return true;
    } catch (error) {
        console.error('发送邮件失败:', error);
        return false;
    }
}

// 发送部署结果通知
async function sendDeployNotification(repoName, branch, success, logs) {
    const transporter = createTransporter();

    const status = success ? '成功' : '失败';
    const subject = `[自动部署通知] ${repoName} (${branch}) 部署${status}`;

    const html = `
    <h2>自动部署通知</h2>
    <p><strong>仓库:</strong> ${repoName}</p>
    <p><strong>分支:</strong> ${branch}</p>
    <p><strong>状态:</strong> <span style="color: ${success ? 'green' : 'red'}">${status}</span></p>
    <p><strong>时间:</strong> ${new Date().toLocaleString()}</p>
    <h3>部署日志:</h3>
    <pre style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow: auto;">${logs}</pre>
  `;

    try {
        await transporter.sendMail({
            from: config.email.user,
            to: config.email.to,
            subject: subject,
            html: html
        });
        console.log('部署通知邮件已发送');
        return true;
    } catch (error) {
        console.error('发送邮件失败:', error);
        return false;
    }
}

module.exports = {
    sendDeployNotification,
    sendDeployStartNotification
};
